﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace PatternSingleton
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    class Singleton
    {
        //饿汉式实现  唯一实例在类加载的时候立刻实例化
        private  static Singleton singleton = new Singleton();  
        private Singleton()
        { }

        public static Singleton getInstance()
        {
            return singleton;
        }
    
    }

    class Singleton2
    {
        //懒汉式 在执行getins时候再实例化   
        //volatile 用于编译器的顺序调整问题  导致先分地址后实例化 出现的空指针异常
        private volatile static Singleton2 singleton2  ;
        private Singleton2()
        { }

        //多线程同步  禁止多线程同时访问到这里 导致实例化多次
        [MethodImpl(MethodImplOptions.Synchronized)]
        public static Singleton2 getInstance()
        {
            if (singleton2 == null)   singleton2 = new Singleton2();
            return   singleton2;
        }

    }

}
